<?php

class DUsers extends DActiveRecord {

    private $curPage = 0;
    private $defaultSort;
    public $old_password;
    public $new_password;
    public $re_password;

    public static function model($className = __CLASS__) {
        return parent::model($className);
    }

    public function tableName() {
        return 'users';
    }

    public function rules() {
        return array(
            array('login_id, full_name, email, password',
                'required'),
            array('login_id, full_name, email, password',
                'length', 'max' => 256),
            array('email', 'email'),
            array('id, last_login', 'safe'),
            array('re_password',
                'compare',
                'on'               => 'insert, update',
                'compareAttribute' => 'password',
                'message'          => Yii::t('DadminModule.msg', 'were_not_match', array(
                    '{0}' => $this->getAttributeLabel('password'),
                    '{1}' => $this->getAttributeLabel('re_password'),
                )),
            ),
            array('activated_flag', 'boolean'),
            array('login_id', 'ext.validators.DupplicateValidator',
                'tableName'   => $this->tableName(),
                'isNewRecord' => $this->isNewRecord,
                'currId'      => $this->id,
            ),
            array('re_password',
                'compare',
                'on'               => 'change_passwd',
                'compareAttribute' => 'new_password',
                'message'          => Yii::t('DadminModule.msg', 'were_not_match', array(
                    '{0}' => $this->getAttributeLabel('new_password'),
                    '{1}' => $this->getAttributeLabel('re_password'),
                )),
            ),
            array('new_password, old_password',
                'required',
                'on' => 'change_passwd'
            ),
            array('old_password',
                'validateOldPassword',
                'on' => 'change_passwd',
            ),
            array('full_name, activated_flag',
                'safe', 'on' => 'search'
            ),
        );
    }

    public function relations() {
        return array();
    }

    /**
     * @return array customized attribute labels (name=>label)
     */
    public function attributeLabels() {
        return array(
            'full_name'       => 'Họ tên',
            'login_id'        => 'Tên đăng nhập',
            'email'           => 'Email',
            'password'        => 'Mật khẩu',
            're_password'     => 'Gõ lại mật khẩu',
            'new_password'    => 'Mật khẩu mới',
            'old_password'    => 'Mật khẩu cũ',
            'last_login' => 'Lần đăng nhập sau cùng',
            'activated_flag'  => 'Có hiệu lực',
        );
    }

    public function search() {
        //Restore state from session
        $this->restoreState();

        //Criteria
        $criteria = new CDbCriteria;
        $criteria->compare('full_name', $this->full_name, true);
        $criteria->compare('activated_flag', $this->activated_flag);

        //Sorting
        $sort               = new CSort();
        $sort->defaultOrder = ($this->defaultSort == '') ? array('id'              => true) : $this->defaultSort;
        $sort->attributes = array(
            'id' => array(
                'asc'       => 'id ASC',
                'desc'      => 'id DESC',
                'default'   => 'desc',
            ),
            'full_name' => array(
                'asc'      => 'full_name ASC',
                'desc'     => 'full_name DESC',
                'default'  => 'asc',
            ),
            'login_id' => array(
                'asc'     => 'login_id ASC',
                'desc'    => 'login_id DESC',
                'default' => 'asc',
            ),
            'email'   => array(
                'asc'            => 'email ASC',
                'desc'           => 'email DESC',
            ),
            'activated_flag' => array(
                'asc'     => 'activated_flag ASC',
                'desc'    => 'activated_flag DESC',
                'default' => 'asc',
            ),
        );
        $sort->applyOrder($criteria);

        return new CActiveDataProvider($this, array(
            'criteria'   => $criteria,
            'sort'       => $sort,
            'pagination' => array('currentPage' => $this->curPage),
        ));
    }

    protected function beforeSave() {
        parent::beforeSave();

        //change password
        if ($this->scenario == 'change_passwd') {
            $this->password = $this->new_password;
        }

        if ($this->getIsNewRecord()) {
            $this->password = $this->encrypt($this->password);
        } else {
            $oldRow         = $this->findByPk($this->id);
            if ($oldRow->password != $this->password)
                $this->password = $this->encrypt($this->password);
        }

        return true;
    }

    private function encrypt($password) {
        return md5($password);
    }

    private function restoreState() {
        $state = SpsState::getState();

        if ($state) {
            if (isset($state['sort']))
                $this->defaultSort = $state['sort'];
            if (isset($state['page']))
                $this->curPage     = $state['page'];

            if (isset($state['search'])) {
                foreach ($state['search'] as $key => $value)
                    if ($value != '')
                        $this->$key = $value;
            }
        }
    }

    /* ------------------------------------------------------------------------
      VALIDATETOR FUNCTIONS
    -------------------------------------------------------------------------*/
    public function validateOldPassword($attribute, $params) {
        $encryptOldPassword = $this->encrypt($this->$attribute);

        if ($encryptOldPassword != $this->password) {
            $this->addError($attribute, Yii::t('DadminModule.message', 'was_incorret', array(
                    '{0}' => $this->getAttributeLabel($attribute),
                )));
            return FALSE;
        } else {
            return TRUE;
        }
    }
    /* ------------------------------------------------------------------------
      //VALIDATETOR FUNCTIONS
    -------------------------------------------------------------------------*/
}